package com.wuyou.sso.common.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wuyou.sso.common.bean.ResultBean;
import com.wuyou.sso.common.contant.CommonConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Locale;

/**
 * @author lishangbu
 * @date 2018/7/8 客户端异常处理 1. 可以根据 AuthenticationException 不同细化异常处理
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    @Override
    public void commence(
            HttpServletRequest request,
            HttpServletResponse response,
            AuthenticationException authException)
            throws IOException {
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        ResultBean<String> result = new ResultBean<>();
        result.setCode(CommonConstants.FAIL);

        if (authException instanceof CredentialsExpiredException
                || authException instanceof InsufficientAuthenticationException) {
            String msg =
                    SpringSecurityMessageSource.getAccessor()
                            .getMessage(
                                    "AbstractUserDetailsAuthenticationProvider.credentialsExpired",
                                    authException.getMessage(),
                                    Locale.CHINA);
            result.setMsg(msg);
        }

        if (authException instanceof UsernameNotFoundException) {
            String msg =
                    SpringSecurityMessageSource.getAccessor()
                            .getMessage(
                                    "AbstractUserDetailsAuthenticationProvider.noopBindAccount",
                                    authException.getMessage(),
                                    Locale.CHINA);
            result.setMsg(msg);
        }

        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(result));
    }
}
